package com.light.applet.oauth.authentication;

import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.Assert;

import java.util.Collection;

/**
 * @author 魏彪
 */
public class WechatAuthenticationToken extends AbstractAuthenticationToken {

    private final Object principal;

    /**
     * 创建一个未认证的对象
     *
     * @param principal   登录用户对象
     */
    public WechatAuthenticationToken(Object principal) {
        super(null);
        this.principal = principal;
        setAuthenticated(false);
    }

    /**
     * 创建一个已认证对象
     *
     * @param authorities 权限
     * @param principal   登录用户对象
     */
    public WechatAuthenticationToken(Collection<? extends GrantedAuthority> authorities, Object principal) {
        super(authorities);
        this.principal = principal;
        // 必须使用super，因为我们要重写
        super.setAuthenticated(true);
    }

    /**
     * 不能暴露Authenticated的设置方法，防止直接设置
     *
     * @param isAuthenticated 是否认证
     * @throws IllegalArgumentException 异常
     */
    @Override
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        Assert.isTrue(!isAuthenticated,
                "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        super.setAuthenticated(false);
    }

    /**
     * 微信静默登录模式下不需要用户凭证
     *
     * @return Object
     */
    @Override
    public Object getCredentials() {
        return null;
    }

    /**
     * 被认证主体的身份，如果是用户名/密码登录，就是用户名
     *
     * @return Object
     */
    @Override
    public Object getPrincipal() {
        return principal;
    }
}
